<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import * as echarts from 'echarts'

const props = defineProps({
  salesTrend: {
    type: Object,
    required: true
  }
})

// 图表实例
let salesTrendChart = null

// 引用
const salesTrendRef = ref(null)

// 初始化销售趋势图
const initSalesTrend = () => {
  if (salesTrendChart) {
    salesTrendChart.dispose()
  }
  
  salesTrendChart = echarts.init(salesTrendRef.value)
  
  const option = {
    backgroundColor: 'transparent',
    grid: {
      left: '5%',
      right: '5%',
      top: '15%',
      bottom: '10%',
      containLabel: true
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    xAxis: {
      type: 'category',
      data: props.salesTrend.months,
      axisLine: {
        lineStyle: {
          color: '#fff'
        }
      },
      axisLabel: {
        color: '#fff',
        fontSize: 10
      }
    },
    yAxis: {
      type: 'value',
      splitLine: {
        lineStyle: {
          color: 'rgba(255, 255, 255, 0.1)'
        }
      },
      axisLabel: {
        color: '#fff',
        fontSize: 10
      }
    },
    series: [
      {
        name: '销售量',
        type: 'line',
        smooth: true,
        data: props.salesTrend.values,
        lineStyle: {
          width: 3,
          color: '#67C23A'
        },
        symbolSize: 6,
        itemStyle: {
          color: '#67C23A'
        },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            {
              offset: 0,
              color: 'rgba(103, 194, 58, 0.4)'
            },
            {
              offset: 1,
              color: 'rgba(103, 194, 58, 0.1)'
            }
          ])
        }
      }
    ]
  };
  
  salesTrendChart.setOption(option);
}

// 窗口大小改变时重绘图表
const handleResize = () => {
  salesTrendChart && salesTrendChart.resize()
}

onMounted(() => {
  initSalesTrend()
  
  // 添加窗口大小改变事件
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  // 移除窗口大小改变事件
  window.removeEventListener('resize', handleResize)
  
  // 销毁图表实例
  salesTrendChart && salesTrendChart.dispose()
})
</script>

<template>
  <dv-border-box-7 class="dashboard-panel">
    <div class="panel-header">销售趋势分析</div>
    <div class="chart-container sales-chart" ref="salesTrendRef"></div>
  </dv-border-box-7>
</template>

<style scoped>
.dashboard-panel {
  position: relative;
  min-height: 300px; /* 设置最小高度 */
  height: 300px; /* 固定高度 */
  flex: 0 0 auto; /* 禁止收缩 */
  overflow: visible; /* 允许内容超出 */
}

.sales-chart {
  flex: 1;
  min-height: 200px;
  margin-top: 5px;
  padding-bottom: 10px;
}

.panel-header {
  flex-shrink: 0;
  margin-bottom: 8px;
}
</style> 